<?php
!defined('IN_FRAME') && die('404 Page');
class m_sys extends Model {
    /* id, name, val, desed */
    
    public function __construct() {
        $this->table = 't_sys';
        parent::__construct();
    }
    
    private function setCacheStorage() {
        phpFastCache::$storage = 'files';
        phpFastCache::$securityKey = 'sys';
        phpFastCache::$path = CACHES_PATH;
    }
    
    public function get($id, $blnReArr = true) {
        $re = false;
        $this->setCacheStorage();
        $arrData = phpFastCache::get('sys');
        if ($arrData && isset($arrData[$id])) {
            $re = $arrData[$id];
        } else {
            $re = $this->getOne(array('id' => $id));
            if ($re && $re['desed'] == 1) {
                $re['val'] = $this->getUnDesed($re['val']);
            }
            $this->refresh();
        }
        if (is_array($re) && !$blnReArr) {
            $re = $re['val'];
        }
        return $re;
    }
    
    public function isKey($str) {
        $arrTemp = array();
        preg_match('/^[0-9a-zA-Z_]{1,85}$/', $str, $arrTemp);
        return count($arrTemp) > 0;
    }
    
    public function getDesed($val) {
        $objDes = new DES();
        return $objDes->encode($val);
    }
    
    public function getUnDesed($val) {
        $objDes = new DES();
        return $objDes->decode($val);
    }
    
    private function refresh() {
        $arrData = $this->select();
        if ($arrData) {
            $arrTemp = array();
            foreach ($arrData as $arr) {
                $arrTemp[$arr['id']] = $arr;
            }
            $this->setCacheStorage();
            phpFastCache::set('sys', $arrTemp, 86400000);
        }
    }
    
    public function update($arrSet, $arrWhere) {
        !is_array($arrWhere) && $arrWhere = array('id' => $arrWhere);
        $re = parent::update($arrSet, $arrWhere);
        $this->refresh();
        return $re;
    }
    
    public function insert($arrData) {
        $re = parent::insert($arrData);
        $this->refresh();
        return $re;
    }
    
    public function delete($arrWhere) {
        !is_array($arrWhere) && $arrWhere = array('id' => $arrWhere);
        $re = parent::delete($arrWhere);
        $this->refresh();
        return $re;
    }
}
